<template>
  <Card v-model="cardtype">
    <div class="md:flex md:mb-5">
      <div class="text-3xl font-semibold" style="color: #4e598c">{{ title }}</div>
    </div>
    <div class="md:flex">
      <Form :model="formState" ref="formRef" class="md:flex-row w-full flex-wrap" v-bind="formItemLayout">
        <div class="md:flex w-full md:justify-between">
          <Col :span="12">
            <FormItem name="time" style="width: 260px" label="时间">
              <RangePicker v-model:value="timeRange" :format="format" />
            </FormItem>
          </Col>
          <Col :span="4">
            <FormItem>
              <div class="md:flex md:justify-end">
                <Button type="primary" shape="circle" @click="onSubmit">
                  <template #icon><SearchOutlined /></template>
                </Button>
                <Button style="margin-left: 5px" shape="circle" @click="resetForm">
                  <template #icon> <RedoOutlined /> </template>
                </Button>
              </div>
            </FormItem>
          </Col>
        </div>
      </Form>
    </div>
    <div class="md:flex">
      <div :id="disBarChartName" style="width: 800%; height: 450%"></div>
    </div>
  </Card>
</template>

<script setup lang="ts">
import { Card, RangePicker, FormItem, Button, Form } from 'ant-design-vue';
import { SearchOutlined, RedoOutlined } from '@ant-design/icons-vue';
import { reactive, ref, defineProps } from 'vue';
import moment, { Moment } from 'moment';
import * as echarts from 'echarts';
import { TenantDistributionReq, TenantDistributionResp } from '/@/api/operation-center/tenant-opertation/source-analysis/model/sourceAnalysisModel';
import {
  getTenantDistributionByChannel,
  getTenantDistributionByIndustry,
  getTenantDistributionByLocation,
} from '/@/api/operation-center/tenant-opertation/source-analysis/sourceAnalysis';

let props = defineProps({
  cardType: String,
});
const formRef = ref();
const cardtype = ref(props.cardType);
const formState = reactive<Record<string, any>>({});

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 24 },
};

// 卡片标题映射定义
let titleMap = { industry: '行业分布', location: '所在地分布', channel: '来源渠道分布' };

// div ID名称映射定义
let disBarChartNameMap = {
  industry: 'industry-bar-chart',
  location: 'location-bar-chart',
  channel: 'channel-bar-chart',
};

// 柱状图颜色映射定义
let barChartColorMap = {
  industry: '#F9C74F',
  location: '#F3722C',
  channel: '#277DA1',
};

// 卡片标题 & 图表标题
const title = props.cardType ? titleMap[props.cardType] : '租户分布';

// 时间范围选择框相关属性
const timeRange = ref<Moment[]>([]);
const format = ref<string>('YYYY-MM-DD');

const disBarChartName = props.cardType ? disBarChartNameMap[props.cardType] : '租户分布';
var option;

let startDate = moment().add(-9, 'months').format('YYYY-MM-DD HH:mm:ss');

let tenantDistributionReq: TenantDistributionReq = {
  startTime: startDate,
  endTime: moment().format('YYYY-MM-DD HH:mm:ss'),
};

let labelList = [];
let valueList = [];
let labelValueList = [];

/**
 * 转换后端返回的转化率List of Map
 * @param distributionMapList 后端返回的转化率List of Map
 * @param labelValueList 待转换的List of key-value Object
 * @param labelList 待转换的日期列表
 * @param valueList 待转换的转化率数值列表
 */
function collectDistributionList(
  distributionMapList: TenantDistributionResp[],
  labelValueList: Array<any>,
  labelList: Array<any>,
  valueList: Array<any>
) {
  for (let i = 0; i < distributionMapList.length; i++) {
    let distributionMap = distributionMapList[i];
    labelValueList.push({
      labelName: distributionMap.labelName,
      value: distributionMap.num,
    });
    labelList.push(distributionMap.labelName);
    valueList.push(distributionMap.num);
  }
}

/**
 * 初始化Echart图
 * @param myChart echat初始化元素
 * @param barColor 柱状图颜色
 * @param labelList 横轴标签列表
 * @param valueList 纵轴值列表
 */
function initEchart(myChart: echarts.ECharts, barColor: string, labelList: Array<string>, valueList: Array<number>) {
  option = {
    title: {
      text: '租户注册数',
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        label: {
          backgroundColor: '#6a7985',
        },
      },
    },
    legend: {
      data: ['转化率'],
    },
    grid: {
      top: '12%',
    },
    xAxis: {
      type: 'category',
      data: labelList,
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        data: valueList,
        type: 'bar',
        showBackground: true,
        color: barColor,
        backgroundStyle: {
          color: 'rgba(180, 180, 180, 0.2)',
        },
      },
    ],
  };
  option && myChart.setOption(option);
}

/**
 * 请求租户分布数据并根据卡片类别，渲染不同统计维度的图表
 * @param tenantDistributionReq 租户分布情况请求体
 */
function requestAndRender(tenantDistributionReq: TenantDistributionReq) {
  labelValueList = [];
  labelList = [];
  valueList = [];
  option = [];

  let chartDom = document.getElementById(disBarChartName);
  let myChart = echarts.init(chartDom);

  if (props.cardType === 'industry') {
    getTenantDistributionByIndustry(tenantDistributionReq).then((res) => {
      // 处理后端返回的List of Map类型
      collectDistributionList(res, labelValueList, labelList, valueList);
      initEchart(myChart, barChartColorMap[props.cardType], labelList, valueList);
    });
  } else if (props.cardType === 'location') {
    getTenantDistributionByLocation(tenantDistributionReq).then((res) => {
      // 处理后端返回的List of Map类型
      collectDistributionList(res, labelValueList, labelList, valueList);
      initEchart(myChart, barChartColorMap[props.cardType], labelList, valueList);
    });
  } else if (props.cardType === 'channel') {
    getTenantDistributionByChannel(tenantDistributionReq).then((res) => {
      // 处理后端返回的List of Map类型
      collectDistributionList(res, labelValueList, labelList, valueList);
      initEchart(myChart, barChartColorMap[props.cardType], labelList, valueList);
    });
  }
}

// 提交表单参数
const onSubmit = async () => {
  formRef.value.validate().then(() => {
    tenantDistributionReq = {
      startTime: timeRange.value[0].format('YYYY-MM-DD HH:mm:ss'),
      endTime: timeRange.value[1].format('YYYY-MM-DD HH:mm:ss'),
    };
    requestAndRender(tenantDistributionReq);
  });
};

// 清空表单参数
const resetForm = () => {
  timeRange.value = [];
};
</script>
